package org.feng.navigation.generator.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.IOException;

/**
 * Freemarker 工具类
 *
 * @version V1.0
 * @author: junzi
 * @date: 2023年02月07日 15时11分
 */
public class FreemarkerUtil {
    private static final String FREEMARKER_TEMPLATES_URL = "templates";

    private static Configuration configuration;

    private static Configuration getConfiguration() {
        if (configuration != null) {
            return configuration;
        }
        configuration = new Configuration(Configuration.VERSION_2_3_32);
        try {
            configuration.setDirectoryForTemplateLoading(FileUtil.getFileByResourceUrl(FREEMARKER_TEMPLATES_URL));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return configuration;
    }

    /**
     * 获取Freemarker模板对象
     *
     * @param templateFileName 模板文件名，比如 <code>GeneratorEnum.java.ftl</code>
     * @return Freemarker模板对象
     */
    public static Template getTemplateByName(String templateFileName) {
        try {
            return getConfiguration().getTemplate(templateFileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
